package co.yixiang.common.security.config;

import co.yixiang.common.security.domain.JwtUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

import static co.yixiang.common.core.constant.SecurityConstants.*;

/**
 * token增强，客户端模式不增强。
 */
public class CustomTokenEnhancer implements TokenEnhancer {

	/**
	 * Provides an opportunity for customization of an access token (e.g. through its
	 * additional information map) during the process of creating a new token for use by a
	 * client.
	 * @param accessToken the current access token with its expiration and refresh token
	 * @param authentication the current authentication including client and user details
	 * @return a new token enhanced with additional information
	 */
	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		JwtUser user = (JwtUser) authentication.getPrincipal();
		final Map<String, Object> additionalInfo = new HashMap<>();
		Map<String, Object> userDetails = new HashMap<>();
		userDetails.put(DETAILS_USER_ID, user.getId());
		userDetails.put(DETAILS_USERNAME, user.getUsername());
		additionalInfo.put(DETAILS_USER, user);
		// Set additional information in token for retriving in #org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint
		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
		return accessToken;
	}

}
